﻿//=============================================================
// Copyright (C) 2015 福流网络
// 作 者：江怀玉
// 日 期：2015-05-11
// 描 述: 通用的数据视图[MINIUI]
// URL Parameter：
//        entity:对应的实体
//        condition:过滤数据条件
//        order:排序字段
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人            修改内容
// 1.00   2015-05-11   江怀玉           
//=============================================================
using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

using FL.SysEntity;
using FL.Bussiness;
using FL.DBModule.Sys;

namespace FL.Web.BackEnd
{
    public partial class DataGrid : ListPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // 权限 
            if (this.FunctionID != null && this.FunctionID != Guid.Empty)
            {
                if (this.UserId == null)
                {
                    Response.Redirect("/Error.aspx?message=1&functionId=" + FunctionID);
                }
                if (!CheckFunctionRight())
                {
                    Response.Redirect("/Error.aspx?message=2&functionId=" + FunctionID);
                }
            }
            SetButtons();
        }

        /// <summary>
        /// 
        /// </summary>
        public override void SetButtons()
        {
            string functionid = GetStringFromQueryString("functionid", "");
            if (functionid == "")
            {
                string menu_code = GetStringFromQueryString("code", "");
                t_sys_function _function = this._bll.GetEntityByCondition<t_sys_function>(string.Format("code='{0}'", menu_code));
                functionid = _function == null ? "" : _function.id.ToString();
            }

            v_user_function_operation function = (new BaseBussnies(new v_user_function_operation())).GetEntityByCondition("function_id='" + functionid + "' and user_id='"+this.UserId.ToString()+"'") as v_user_function_operation;
            string userID = this.UserId.ToString();
            if (function == null)
            {
                BtnItems = "";
                BtnEvents = "";
                InitBtnEvents = "";
            }
            else
            {
                string[] btns = function.names.Split(',');
                string[] btnTexts = function.captions.Split(',');
                string[] fns = function.actions.Split(',');
                string[] barItems = function.BarItems.Split(',');
                string[] css = function.iconcss.Split(',');
                string[] area = function.places.Split(',');
                if (barItems == null)
                {
                    BtnItems = "";
                    BtnEvents = "";
                    InitBtnEvents = "";
                    return;
                }
                if (barItems.Count() == 0)
                {
                    BtnItems = "";
                    BtnEvents = "";
                    InitBtnEvents = "";
                    return;
                }
                //生成按钮
                StringBuilder strHTML = new StringBuilder("");
                for (int i = 0; i < btns.Length; i++)
                {
                    foreach (string item in barItems)
                    {

                        if (item == btns[i])
                        {
                            string strFormater = "<a class=\"mini-button\"  iconcls=\"{0}\" plain=\"true\"  onclick=\"{1}\" id=\"{3}\" place=\"{4}\">{2}</a>";
                            string strItem = string.Format(strFormater, css[i], fns[i], btnTexts[i], btns[i], area[i]);
                            if (opertionItems.Where(p => p.item == strItem).Count() == 0)
                            {
                                strHTML.Append(strItem);
                                opertionItems.Add(new OpertionItems { area = area[i], item = strItem });
                            }
                            break;
                        }
                        //else
                        //{
                        //    if (this.User!=null&&this.User.username== "admin")
                        //    {
                        //        string strFormater = "<a class=\"mini-button\"  iconcls=\"{0}\" plain=\"true\"  onclick=\"{1}\" id=\"{3}\" place=\"{4}\">{2}</a>";
                        //        string strItem = string.Format(strFormater, css[i], fns[i], btnTexts[i], btns[i], area[i]);
                        //        strHTML.Append(strItem);
                        //        opertionItems.Add(new OpertionItems { area = area[i], item = strItem });
                        //        break;
                        //    }
                        //}
                    }
                }
                //for (int i = 0; i < btns.Length; i++)
                //{
                //    if (barItems.Contains(btns[i]) || this.UserName.ToLower() == "admin")
                //    {
                //        string strFormater = "<a class=\"mini-button\"  iconcls=\"{0}\" plain=\"true\"  onclick=\"{1}\" id=\"{3}\" place=\"{4}\">{2}</a>";
                //        string strItem = string.Format(strFormater, css[i], fns[i],btnTexts[i],btns[i],area[i]);
                //        strHTML.Append(strItem);
                //        opertionItems.Add(new OpertionItems { area = area[i], item = strItem });

                //    }
                //}
                BtnItems = strHTML.ToString();
            }
        }

        public IList<OpertionItems> opertionItems = new List<OpertionItems>();

        /// <summary>
        /// 获取不同区域的操作项
        /// </summary>
        /// <param name="area">约定的区域（left,center,top,right,context_menu)</param>
        /// <returns></returns>
        public string getItem(string area)
        { 
            var _items = opertionItems.Where(p=>p.area==area).ToList();
           StringBuilder strHTML = new StringBuilder("");
           if (_items == null)
           {
               return "";
           }
           foreach (var _item in _items)
           {
               strHTML.Append(_item.item);
           }
           return strHTML.ToString();
        }


        /// <summary>
        /// 生成数据列头和数据对象
        /// </summary>
        /// <returns></returns>
        public override string CreateDataGridColumns()
        {
            
            //if (list == null)
          
            t_set_datagrid template = new t_set_datagrid();
            BaseBussnies<t_set_datagrid> bll = new BaseBussnies<t_set_datagrid>(template);

            
            System.Data.DataTable dt = bll.GetDataBySqlComm(string.Format("select * from t_sys_user_datagrid_config where add_user='{0}' and function_id='{1}'", this.UserId, this.FunctionID));
            string json = string.Empty;

            if (dt!=null&&dt.Rows.Count > 0)
            {
                json = dt.Rows[0].ItemArray[2].ToString();
            }
            IList<t_set_datagrid> _new_list = null;
            if (!string.IsNullOrEmpty(json))
            {
                _new_list = FL.Common.Globals.JSONtoOject<t_set_datagrid>("t_set_datagrid", json.Replace("add_user", "add_user_1").Replace("add_time", "add_time_1"));
            }
            if (_new_list == null)
            {
                _new_list = bll.GetEntityListByCondition<t_set_datagrid>(" entity='" + EntityName + "' and is_visiable<>'N'");
            }
            //var _new_list = bll.GetEntityListByCondition<t_set_datagrid>(" entity='" + EntityName + "' and is_visiable<>'N'");
            
            string _strHtml = "key:'{0}',label:'{1}',width:{2},{3}";
            if (list == null)
            {
                return ("{" + string.Format(_strHtml, "Not Data", "Not Data", 400, "formatter:\"\"") + "},");
            }
            StringBuilder _sbHtml = new StringBuilder("");
            var _list = _new_list.Where(p => p.is_visiable == "Y").OrderBy(p => p.sort).ToList();
            int i = 0;
            string _header = "";
            foreach (t_set_datagrid _template in _list)
            {
                i = i + 1;
                if (_header != _template.header)
                {
                    if (!_template.is_created&&!string.IsNullOrEmpty(_template.header))
                    {
                        _header = _template.header;
                        var _tlist = _list.Where(p => p.header == _header);
                        _sbHtml.Append(string.Format("<div header=\"{0}\"><div property=\"columns\">", _header));
                        foreach (t_set_datagrid _t in _tlist)
                        {
                            _t.is_created = true;
                            // 默认那个0.00为空
                            if (string.IsNullOrEmpty(_t.data_formatter) && (_t.data_type == "numeric" || _t.data_type == "float" ||  _t.data_type == "decimal"||_t.data_type.Contains("date")))
                            {
                                _t.data_formatter = "fnDefaultFormat";
                            }
                            if (string.IsNullOrEmpty(_t.column_type))
                            {
                                if (AllowEdit)
                                {
                                    _sbHtml.Append(string.Format("<div field=\"{0}\" name=\"{0}\" width=\"{1}\" headerAlign=\"center\" allowSort=\"true\" renderer=\"{5}\">{2}<input property=\"editor\" class=\"mini-{4}\" style=\"width:100%;\" {3} /></div>\n",
                                        _t.name,
                                        _t.width,
                                        _t.caption,
                                        (!string.IsNullOrEmpty(_t.data_source_type) && !string.IsNullOrEmpty(_t.data_source) ? string.Format(" data=\"{0}_data\"", _t.name) : ""),
                                        string.IsNullOrEmpty(_t.editor) ? "textbox" : _t.editor, _t.data_formatter)
                                      );
                                }
                                else
                                {
                                    _sbHtml.Append(string.Format("<div field=\"{0}\"  name=\"{0}\" width=\"{1}\" headerAlign=\"center\" allowSort=\"true\"  renderer=\"{3}\" >{2}</div>\n", _t.name, _t.width, _t.caption, _t.data_formatter));
                                }
                            }
                            else
                            {
                                _sbHtml.Append(string.Format("<div field=\"{0}\"  name=\"{0}\" width=\"{1}\" headerAlign=\"center\" allowSort=\"true\" type=\"{3}\"  renderer=\"{5}\" >{2}<input property=\"editor\" class=\"mini-{4}\" style=\"width:100%;\" data=\"{0}_data\" /></div>\n", _t.name, _t.width, _t.caption, _t.column_type, string.IsNullOrEmpty(_t.editor) ? _t.column_type.Replace("column", "") : _t.editor, _t.data_formatter));
                            }
                        }
                        _sbHtml.Append("</div></div>");
                    }
                   
                }
                if (_template.is_created)
                {
                    continue;
                }
                //不相等，但不为空
                if (_header == _template.header & !string.IsNullOrEmpty(_header))
                {
                    continue;
                }
                if (string.IsNullOrEmpty(_template.column_type))
                {
                    // 默认那个0.00为空
                    if (string.IsNullOrEmpty(_template.data_formatter) && (_template.data_type == "numeric" || _template.data_type == "float" || _template.data_type == "decimal" || _template.data_type.Contains("date")))
                    {
                        _template.data_formatter = "fnDefaultFormat";
                    }
                    if (AllowEdit)
                    {
                        _sbHtml.Append(string.Format("<div field=\"{0}\"  name=\"{0}\" width=\"{1}\" headerAlign=\"center\" allowSort=\"true\">{2}<input property=\"editor\" class=\"mini-{4}\" style=\"width:100%;\" {3}   renderer=\"{5}\"/></div>\n",
                            _template.name,
                            _template.width,
                            _template.caption,
                            (!string.IsNullOrEmpty(_template.data_source_type) && !string.IsNullOrEmpty(_template.data_source) ? string.Format(" data=\"{0}_data\"", _template.name) : ""),
                            string.IsNullOrEmpty(_template.editor) ? "textbox" : _template.editor, _template.data_formatter));
                    }
                    else
                    {
                        if (_template.column_type == "checkboxcolumn")
                        {
                            _sbHtml.Append(string.Format("<div field=\"{0}\"  name=\"{0}\" width=\"{1}\"  headerAlign=\"center\" allowSort=\"true\"  renderer=\"{3}\">{2}</div>\n", _template.name, _template.width, _template.caption, _template.data_formatter));
                        }
                        else
                        {
                            _sbHtml.Append(string.Format("<div field=\"{0}\"  name=\"{0}\" width=\"{1}\"  headerAlign=\"center\" allowSort=\"true\"  renderer=\"{3}\">{2}</div>\n", _template.name, _template.width, _template.caption, _template.data_formatter));
                        }
                    }
                }
                else
                {
                    if (_template.column_type == "checkboxcolumn")
                    {

                        _sbHtml.Append(string.Format("<div field=\"{0}\"  name=\"{0}\" width=\"{1}\" trueValue=\"1\" falseValue=\"0\" headerAlign=\"center\" allowSort=\"true\" type=\"{3}\"  renderer=\"{5}\" ctrlClass=\"{4}\">{2}</div>\n", _template.name.Trim(), _template.width, _template.caption, _template.column_type, string.IsNullOrEmpty(_template.editor) ? _template.column_type.Replace("column", "") : _template.editor, _template.data_formatter));
                    }
                    else
                    {
                        _sbHtml.Append(string.Format("<div field=\"{0}\"  name=\"{0}\" width=\"{1}\" headerAlign=\"center\" allowSort=\"true\" type=\"{3}\">{2} <input property=\"editor\" class=\"mini-{4}\" style=\"width:100%;\" data=\"{0}_data\"  renderer=\"{5}\"/></div>\n", _template.name, _template.width, _template.caption, _template.column_type, _template.column_type.Replace("column", ""), _template.data_formatter));
                    }
                }
            }
            //_sbHtml.Remove(_sbHtml.Length - 1, 1);
            return (_sbHtml.ToString());
        }
    }

    public class OpertionItems
    {
        public string area
        {
            get;
            set;
        }

        public string item
        {
            get;
            set;
        }
    }
}